#include <cstdlib>
#include<iostream>
#include<vector>
#include<algorithm>
using namespace std;
class Solution {
public:
    int threeSumClosest(vector<int>& nums, int target) {
        sort(nums.begin(),nums.end());
        int n=nums.size(),sum=0,ans=nums[0]+nums[1]+nums[2];
        for(int i=0;i<n-2;i++)
        {
            if(i&&nums[i-1]==nums[i])continue;
            int l=i+1,r=n-1;
            while(l<r)
            {
                int sum=nums[i]+nums[l]+nums[r];
                if(abs(target-sum)<abs(target-ans))
                    ans=sum;
                if(sum<target)l++;
                if(sum>target)r--;
                if(nums[l]+nums[r]+nums[i]==target)return target;
            }
        }
        return ans;
    }
};